package cn.wenhaha.install.controller;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.wenhaha.common.bean.dto.install.DataSourceDTO;
import cn.wenhaha.common.core.controller.BaseController;
import cn.wenhaha.install.service.IIndexService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.Map;
import java.util.Objects;

@Controller
@RequestMapping("/install")
public class IndexController extends BaseController {

    private String prefix = "install/index/";

    @Autowired
    private IIndexService indexService;

    @GetMapping()
    public Object index(HttpSession session, Model model, Integer step, Integer dbType)
    {
        if (step==null){step=0;}
        Object install_error = session.getAttribute("install_error");
        if(FileUtil.exist(System.getProperty("user.dir") + "/config/install.lock")){
            return  error("当前已完安装，如需重新安装，请关闭项目，删除相关文件！");
        }
        switch (step){
            case 2:
                session.setAttribute("install_error",false);
                return  step2(session,model);
            case 3:
                if (Objects.isNull(install_error) ||(Boolean)install_error) {
                    return  error("环境检测未通过，不能进行下一步操作！");
                }else if(dbType==null || (dbType!=0 && dbType!=1)){
                    return  error("错误的数据库类型");
                }
                if (dbType.equals(0)){
                    return prefix+"step3";
                }else {
                    return  step3Sqlite(session,model);
                }
            case 4:
                if (Objects.isNull(install_error) ||(Boolean)install_error) {
                    return  error("环境检测未通过，不能进行下一步操作！");
                }
                return  error("非法访问！");
            case 5:
                if (Objects.isNull(install_error) ||(Boolean)install_error) {
                    return  error("初始失败！");
                }
            default:
                return prefix+"index";
        }


    }

    private String step3Sqlite(HttpSession session, Model model) {
        model.addAttribute("dir",System.getProperty("user.dir")+ File.separator+"sync.db");
        return prefix+"step3_sqlite";
    }

    @PostMapping
    @ResponseBody
    public Object indexPost(DataSourceDTO dataSourceDTO, HttpSession session, Integer step) {
        if (step==null||step!=5){ error("非法访问！");}
        Object install_error = session.getAttribute("install_error");
        if (Objects.isNull(install_error) ||(Boolean)install_error) {
            return  error("环境检测未通过，不能进行下一步操作！");
        }
        String s = null;
        if (step==4 && dataSourceDTO.getDbType()==0){
            if (ObjectUtil.hasEmpty(dataSourceDTO.getHostname(),dataSourceDTO.getDatabase(),
                    dataSourceDTO.getUsername(),
                    dataSourceDTO.getHostport(), dataSourceDTO.getPassword())){
                return error("数据库配置的全部字段不允许为空！");
            }
            s = indexService.connectDb(dataSourceDTO);

        }else if (step==4 && dataSourceDTO.getDbType()==1){
            if (ObjectUtil.hasEmpty(dataSourceDTO.getDbUri())){
                return error("路径不允许为空！");
            }
            s=indexService.connectSQLite(dataSourceDTO.getDbUri());

        }
        if (s==null){
            return error("非法访问!");
        }

        if (!StrUtil.contains(s,"数据库连接成功")){
            return error(s);
        }
        return success(s);

    }


    @PostMapping("last")
    public Object step5(DataSourceDTO dataSourceDTO,HttpSession session,Integer step){
        if (step==null||step!=5){ error("非法访问！");}
        Object install_error = session.getAttribute("install_error");
        if (Objects.isNull(install_error) ||(Boolean)install_error) {
            return  error("环境检测未通过，不能进行下一步操作！");
        }
        if (StrUtil.hasEmpty(dataSourceDTO.getAccount(),dataSourceDTO.getAdminpwd())){
            return error("请填写管理账号和密码!");
        }
        if (dataSourceDTO.getAdminpwd().length()<6||dataSourceDTO.getAdminpwd().length()>20){
            return error("密码长度在6-20位之间");
        }
        if(FileUtil.exist(System.getProperty("user.dir") + "/config/error.log")){
            FileUtil.del(System.getProperty("user.dir") + "/config/error.log");
        }
        String install = indexService.install(dataSourceDTO);
        if(!StrUtil.contains(install,"系统配置成功")){
            return error(install);
        }
        session.setAttribute("install_last",true);
        return success(install,"/install/restart");
    }

    @GetMapping("restart")
    public Object last(HttpSession session){
        Object install_last = session.getAttribute("install_last");
        if (install_last==null) return error("非法访问");
        if (!(Boolean)install_last){ return error("请正常安装本系统");}

        return prefix+"last";
    }


    @PostMapping("restart")
    @ResponseBody
    public Object restart() throws ClassNotFoundException {
        ThreadUtil.execute(()->{
            synchronized (IndexController.class){
                String s = indexService.exSql();
                if(!StrUtil.contains(s,"安装成功")){
                    File file = FileUtil.touch(System.getProperty("user.dir") + "/config/error.log");
                    FileUtil.writeString(s,file, CharsetUtil.CHARSET_UTF_8);
                }else {
                    FileUtil.touch(System.getProperty("user.dir") + "/config/install.lock");
                }
            }
        });
        return success();
    }


    @PostMapping("test")
    @ResponseBody
    public  Object test(){
        if(FileUtil.exist(System.getProperty("user.dir") + "/config/error.log")){
            String error = FileUtil.readString(System.getProperty("user.dir") + "/config/error.log", CharsetUtil.CHARSET_UTF_8);
            return error(error);
        }
        boolean install=FileUtil.exist(System.getProperty("user.dir") + "/config/install.lock");
        return install?success("安装完成"):success("正在安装中");
    }


    private String step2(HttpSession session,Model model){
        String[][] dir = indexService.checkDir();
        Map<String, String> nvv = indexService.checkNnv();
        if ("no".equals(dir[0][4])){
            session.setAttribute("install_error",true);
        }
        model.addAttribute("data",dir);
        model.addAttribute("nnv",nvv);
        return  prefix+"step2";
    }


}
